//获取应用实例
const $ = require('../../utils/utils');
const user = require('../../manager/userManager.js')
const config = require('../../config.js')
const ImgLoader = require('../../plugin/img-loader/img-loader.js')
var app = getApp();

Page({
    data: {
        footerConfig: {
            pageEvent: true,
            isLogin: true,
            loadingText: "正在努力的加载数据...",
            wishCount: 0
        },
        activeIndex: "0",
        themeSelActive: "",
        isSelcted: false,
        isSelcted_02: false,
        age_data: [],
        age_code: "",
        theme_type_code: "0000",
        intel_code: "0",
        tag_data: "",
        bookShelfCode: "",
        bookList: [],
        pageno: 1,
        pagesize: 12,
        hasMoreData: true,
        area: "",
        user_longitude: 0.0,
        user_latitude: 0.0,
        shelfList: [],
        prevPageFlag: 0,
        pattern_status: true,
        inviteShow: false,
        collection_nor: '../../img/wishList_nor.png',
        collection_sel: '../../img/HaveWishList.png',
        activityIcon: '../../img/activityIcon.png',
        isNotFrist: true,
        welcome_img: "http://wdb007.oss-cn-hangzhou.aliyuncs.com/wxapp/images/1_2-8.png",
        img_no: 1,
        path: "",
        activityCount: 0,
        activityAlreayCount: 0,
        activityArr: 0,
        isLoadingData: false // 是否在请求数据
    },


    /*************life cycle********/


    onLoad: function (options) {
        var that = this
        this.imgLoader = new ImgLoader(this, this.imageOnLoad.bind(this))
        console.log('# index_onLoad(' + JSON.stringify(options) + wx.getStorageSync('area') + ')')
        if (options.path) {
            this.setData({
                bookShelfCode: wx.getStorageSync('bookShelfCode'),
                area: wx.getStorageSync('area')
            });
            console.log('getBookList------1')
            this.getBookList();
            this.setData({
                path: options.path
            })
        }


        if (!wx.getStorageSync("isNotFrist")) {
            this.setData({
                isNotFrist: false
            })
        }

        if (app.globalData.bookShelfId.length > 0 && wx.getStorageSync("isReLaunch")) {
            app.getClearBookshelfCode(app.globalData.bookShelfId, function (isCorrect, data) {
                if (isCorrect) {
                    wx.setStorageSync("area", data.area)
                    wx.setStorageSync("bookShelfCode", data.bookshelf_code)
                    console.log("getClearBookshelfCode" + data)
                    that.setData({
                        area: data.area,
                    });
                    console.log('getBookList------2')
                    that.getBookList()
                } else {
                    that.getCloseBookshelf();
                }


            })
        }
    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (option) {
        console.log('# index_onShow()')
        var that = this;
        if (wx.getStorageSync('isToLottery')) {
            wx.setStorageSync('isToLottery', false)
            $.goto(config.page.activityLottery)
        }
        app.addListener(function (changedData) {
            console.log("#index_addListener()", wx.getStorageSync("isLogin"))
            that.configFooterConfig()
        });


        that.activityCount()
        // 判断用户是否登陆
        let islogin = wx.getStorageSync("isLogin")
        let wishCount = 0
        if (islogin) {
            wishCount = wx.getStorageSync("wishCount")
        }
        that.setData({
            footerConfig: {
                pageEvent: true,
                isLogin: islogin,
                loadingText: "正在努力的加载数据...",
                wishCount: wishCount
            }
        })
        if (wx.getStorageSync("activityShow")) {
            that.setData({
                inviteShow: true
            });
        }

        if (wx.getStorageSync("isBackFromWishList")) {
            wx.setStorageSync('isBackFromWishList', false)
            this.setData({
                area: wx.getStorageSync("area"),
                bookList: [],
                pageno: 1
            })
            console.log('getBookList------3')
            this.getBookList();
        }

        if (wx.getStorageSync('isBackFromShelfList')) {
            wx.setStorageSync('isBackFromShelfList', false)
            this.refreshShelfData();
        }

        if (wx.getStorageSync("isReLaunch")) {
            if (app.globalData.bookShelfId.length > 0) {
                return
            }
            that.getCloseBookshelf();
            wx.setStorageSync("isReLaunch", false)
        }


        console.log("#index_onShow()", this.data.bookShelfCode, wx.getStorageSync('bookShelfCode'))

        if (this.data.bookShelfCode !== wx.getStorageSync('bookShelfCode')) {
            this.setData({
                area: wx.getStorageSync("area"),
                bookList: [],
                pageno: 1
            })
            console.log('getBookList------4')
            this.getBookList();
        }

        console.log("#index_Show()", wx.getStorageSync("isLogin"))
    },

    onReady: function () {
        console.log('# index_onReady()')
        let that = this
        this.getAges();
        if (this.data.path.length > 0) {
            return;
        }

        if (app.globalData.bookShelfId.length > 0 && wx.getStorageSync("isReLaunch")) {
            return
        }
        this.refreshShelfData();
    },

    onHide: function () {
        console.log('# index_onHide()')
        wx.setStorageSync('scanFlag', 0); //设置扫码标识
    },

    //  监听用户向上滑动
    onReachBottom: function () {
        console.log('# index_onReachBottom()');
        var that = this;
        if (that.data.hasMoreData) {
            that.setData({
                pageno: that.data.pageno + 1
            })
            console.log('getBookList------5')
            that.getBookList();
        } else {
            wx.showToast({
                title: '没有更多数据',
                duration: 2000,
            });
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        console.log("buttom", res);
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target);
        }
        return {
            title: '你身边的书柜,开启绘本阅读新模式我的邦.智能童书馆',
            imageUrl: 'http://wdb007.oss-cn-hangzhou.aliyuncs.com/wxapp/images/indexShare.png',
            path: config.page.index,
            success: function (res) {
                console.log("分享成功", wx.getStorageSync("hdCardInitiatorId"));
            },
            fail: function (res) {
                // 转发失败
                console.log("fail");
            }
        }
    },


    /********************* Methods*****************/

    // 配置footer信息
    configFooterConfig: function () {
        let wishCount = 0
        if (wx.getStorageSync("isLogin")) {
            wishCount = wx.getStorageSync("wishCount")
        }
        var that = this;
        let changedData = wx.getStorageSync("isLogin")
        that.setData({
            footerConfig: {
                pageEvent: true,
                isLogin: changedData,
                loadingText: "正在努力的加载数据...",
                wishCount: wishCount
            }
        })
    },


    // 获取活动列表数量
    activityCount: function () {
        let url = $.getUrl(config.activityCount)
        $.get(url).then(data => {
            this.setData({
                activityCount: data.detail.activityCount
            })
            let activityAlreayCount = wx.getStorageSync("activityAlreayCount")
            let activityArr = this.data.activityCount - activityAlreayCount
            this.setData({
                activityArr: activityArr
            })


        })
    },

    tapWelcome: function () {
        if (this.data.img_no == 3) {
            wx.setStorageSync('isNotFrist', true)
            this.setData({
                isNotFrist: true
            })
        } else {
            let no = this.data.img_no + 1
            this.setData({
                img_no: no,
                welcome_img: "http://wdb007.oss-cn-hangzhou.aliyuncs.com/wxapp/images/" + no + "_2-8.png"
            })
        }

    },

    bindSubmit: function (e) {
        user.saveMsgFormId(e.detail.formId)
    },
    // 遍历书籍列表
    bookList: function (list, index) {
        var that = this;
        var selected = list[index].selected;
        list[index].selected = !selected;
        that.setData({
            bookList: list
        });
    },

    // 加入心愿单 || 移除心愿单
    add_wishList: function (e) {
        let that = this
        if (!wx.getStorageSync("isLogin")) {
            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                //FIXME 调用后台接口获取用户信息
                app.aesPhoneNumber(e.detail.iv, e.detail.encryptedData).then(data => {
                    if (!wx.getStorageSync("isLogin")) {
                        $.goto('../login/login')
                        return;
                    }
                    let index = e.target.dataset.index
                    console.log(e.target)
                    let url = e.target.dataset.selected == false ? config.saveWishBook : config.removeWishBook;
                    let params = {
                        userid: wx.getStorageSync('userid'),
                        usertoken: wx.getStorageSync('usertoken'),
                        isbn: e.target.dataset.bookisbn
                    }

                    $.post(url, params).then(data => {
                        if (data.result == 1) {
                            let message = e.target.dataset.selected == false ? '已加入书架' : '已从书架移除';
                            let wishCount = that.data.footerConfig.wishCount
                            if (!e.target.dataset.selected) {
                                wishCount = wishCount + 1

                            } else {
                                wishCount = wishCount - 1
                            }
                            wx.setStorageSync('wishCount', wishCount)

                            let pageEvent = that.data.footerConfig.pageEvent
                            let isLogin = that.data.footerConfig.isLogin
                            let loadingText = that.data.footerConfig.loadingText
                            that.setData({
                                footerConfig: {
                                    pageEvent: pageEvent,
                                    isLogin: true,
                                    loadingText: loadingText,
                                    wishCount: wishCount
                                }
                            })
                            that.bookList(that.data.bookList, index);
                            wx.showToast({
                                title: message,
                                duration: 1000
                            });
                        }
                    })

                })
            } else if (e.type == "getphonenumber") {
                if (!wx.getStorageSync("isLogin")) {
                    $.goto('../login/login')
                    return;
                }
            }

        } else {
            let index = e.target.dataset.index
            console.log(e.target)
            let url = e.target.dataset.selected == false ? config.saveWishBook : config.removeWishBook;
            let params = {
                userid: wx.getStorageSync('userid'),
                usertoken: wx.getStorageSync('usertoken'),
                isbn: e.target.dataset.bookisbn
            }

            $.post(url, params).then(data => {
                if (data.result == 1) {
                    let message = e.target.dataset.selected == false ? '已加入书架' : '已从书架移除';
                    let wishCount = this.data.footerConfig.wishCount
                    if (!e.target.dataset.selected) {
                        wishCount = wishCount + 1

                    } else {
                        wishCount = wishCount - 1
                    }
                    wx.setStorageSync('wishCount', wishCount)

                    let pageEvent = this.data.footerConfig.pageEvent
                    let isLogin = this.data.footerConfig.isLogin
                    let loadingText = this.data.footerConfig.loadingText
                    that.setData({
                        footerConfig: {
                            pageEvent: pageEvent,
                            isLogin: isLogin,
                            loadingText: loadingText,
                            wishCount: wishCount
                        }
                    })
                    this.bookList(this.data.bookList, index);
                    wx.showToast({
                        title: message,
                        duration: 1000
                    });
                }
            })
        }


    },

    /********************筛选事件**************/

    // 点击年龄段事件处理函数
    ageSort: function (e) {
        var that = this;
        that.setData({
            activeIndex: e.currentTarget.id,
            age_code: e.target.dataset.readable,
            pageno: 1,
            bookList: []
        });
        console.log('getBookList------6')
        that.getBookList();
    },

    /********************跳转相关***********/
    // 进入书籍详情页
    enterBookDetail: function (e) {
        let dataset = e.currentTarget.dataset;
        wx.setStorageSync("book_detail_isbn", dataset.isbn);
        let url = config.page.bookDetail + '?book_isbn=' + dataset.isbn + '&book_name=' + $.subChineseString(dataset.name, 20, true)
        $.goto(url)
    },

    // 扫码
    scanCode: function (e) {
        var that = this
        if (!wx.getStorageSync("isLogin")) {
            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                //FIXME 调用后台接口获取用户信息
                app.aesPhoneNumber(e.detail.iv, e.detail.encryptedData, "scanCode").then(data => {
                    let wishCount = wx.getStorageSync("wishCount")
                    that.setData({
                        footerConfig: {
                            pageEvent: true,
                            isLogin: true,
                            loadingText: "正在努力的加载数据...",
                            wishCount: wishCount
                        }
                    })
                    app.scanCode()
                })
            } else if (e.type == "getphonenumber") {
                app.scanCode()
            }

        } else {
            app.scanCode()
        }



    },

    // 个人中心页面
    gotoUserCenter: function (e) {
        let that = this
        console.log("#index_gotoUserCenter()", wx.getStorageSync("isLogin"))
        if (!wx.getStorageSync("isLogin")) {
            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                app.aesPhoneNumber(e.detail.iv, e.detail.encryptedData).then(data => {
                    that.toPage()
                })
            } else if (e.type == "getphonenumber") {
                that.toPage()
            }
        } else {
            $.goto(config.page.userCenter, false)
        }

    },

    toPage: function () {
        if (wx.getStorageSync('isLogin')) {
            $.goto(config.page.userCenter, false)
        } else {
            $.goto(config.page.login)
        }
    },

    toSelectBookPage: function (e) {
        let that = this
        if (!wx.getStorageSync("isLogin")) {
            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                //FIXME 调用后台接口获取用户信息
                app.aesPhoneNumber(e.detail.iv, e.detail.encryptedData).then(data => {
                    that.gotoWishList()
                })
            } else if (e.type == "getphonenumber") {
                that.gotoWishList()
            }
        } else {
            that.gotoWishList()
        }


    },

    gotoWishList: function () {
        if (wx.getStorageSync('isLogin')) {
            $.goto(config.page.wishList, false)
        } else {
            $.goto(config.page.login)
        }
    },
    // 活动列表页面
    gotoActivity: function () {
        $.goto(config.page.activityList)
    },
    /****************活动相关********/
    // 关闭邀请
    shut_shadow: function () {
        var that = this;
        that.setData({
            inviteShow: true
        });
        wx.setStorageSync("activityShow", 2);
    },

    // 发起邀请
    start_invite: function () {
        wx.setStorageSync("activityShow", 1);
        app.start_invite();
    },

    /****************书柜位置相关********/

    // 根据当前坐标获取书柜信息
    getCloseBookshelf: function () {
        console.log('# index_getCloseBookshelf()')
        var that = this;
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                var latitude = res.latitude;
                var longitude = res.longitude;
                console.log(`当前位置${latitude, longitude}`);
                wx.setStorageSync('current_longitude', longitude);
                wx.setStorageSync('current_latitude', latitude);
                that.getCurrentLocation()
            },
            fail: function (e) {
                console.log(e);
                wx.setStorageSync('current_longitude', 121.442000);
                wx.setStorageSync('current_latitude', 31.156000);
                that.getCurrentLocation()
            },
            // complete: function () {
            //     app.getUserInfo();//获取用户信息
            // }
        })
    },

    // 获取最近的书柜
    getCurrentLocation: function () {
        console.log('# index_getCurrentLocation()')

        if (wx.getStorageSync("isBeginScanCode")) {
            wx.setStorageSync("isBeginScanCode", false)
            return
        }

        let params = {
            user_longitude: wx.getStorageSync('current_longitude'),
            user_latitude: wx.getStorageSync('current_latitude'),
            map_type: 0
        }
        let url = $.getUrl(config.queryNearestShelf, params)
        $.get(url).then(data => {
            wx.setStorageSync('bookShelfCode', data.detail.bookshelf_code)
            wx.setStorageSync('area', data.detail.area)
            this.setData({
                bookShelfCode: data.detail.bookshelf_code,
                area: data.detail.area,
                pageno: 1,
                bookList: []
            });
            console.log('getBookList------7')
            this.getBookList();
        })
    },

    /***************数据获取相关*********/
    // 获取书库列表接口
    getBookList: function (data) {
        let that = this
        this.setData({
            isLoadingData: true
        })


        let url = config.queryShelfBookList
        let params = {
            userid: wx.getStorageSync('userid'),
            shelf_code: wx.getStorageSync('bookShelfCode'),
            pagesize: this.data.pagesize,
            pageno: this.data.pageno,
            readable: this.data.age_code,
        }

        console.log('# index_getBookList()', params)
        url = $.getUrl(url, params)
        $.get(url).then(data => {
            console.log('# index_getBookList()_success', data, params)
            data.items.forEach(item => {
                if (item.favorite == 0) item.selected = false
                else item.selected = true
            })

            let contentlistTem
            if (this.data.pageno != 1) {
                contentlistTem = this.data.bookList;
            } else {
                contentlistTem = []
            }


            let completeList = contentlistTem.concat(data.items)
            let lazyList = completeList.map(item => {
                item.loaded = false
                return item
            })

            if (data.items.length < this.data.pagesize) {
                this.setData({
                    bookList: lazyList,
                    hasMoreData: false
                })
            } else {
                this.setData({
                    bookList: lazyList,
                    hasMoreData: true,
                });
            }
            that.loadImages()

            this.setData({
                isLoadingData: false
            })
        })
    },

    // 获取年龄段标签接口
    getAges: function () {
        console.log('# index_getAges()')
        var Object = []
        let url = config.queryTopicalAgeList
        $.get(url).then(data => {
            console.log(data);
            var obj = {};
            obj.readable = "";
            obj.age = "全部";
            Object.push(obj);
            for (var i = 0; i < data.detail.ages.length; i++) {
                var list = data.detail.ages[i];
                Object.push(list);
            }
            this.setData({
                age_data: Object,
                tag_data: data.detail.topicals
            });

        })


    },

    // 当前书柜列表
    selectShelf: function () {
        console.log('# index_selectShelf()')
        $.goto(config.page.shelfMap)

    },

    // 切换书柜后刷新数据
    refreshShelfData: function () {
        console.log('# index_refreshShelfData()')
        var that = this;
        if (that.data.prevPageFlag == 1) {
            that.setData({
                activeIndex: "0",
                themeSelActive: "",
                isSelcted: false,
                isSelcted_02: false,
                age_code: "",
                theme_type_code: "0000",
                intel_code: "0",
                pageno: 1,
                bookList: [],
            });
        }
        // 获取年龄段标签
        // 获取书库列表
        if ((that.data.bookShelfCode == "" && that.data.prevPageFlag == 0)) {
            if (wx.getStorageSync('bookShelfCode')) {
                that.setData({
                    bookShelfCode: wx.getStorageSync('bookShelfCode'),
                    area: wx.getStorageSync('area')
                });
                console.log('getBookList------8')
                that.getBookList();
                that.getCloseBookshelf();
            }
        } else if (that.data.prevPageFlag == 1) {
            console.log('getBookList------9')
            that.getBookList();
        } else {
            if (wx.getStorageSync("isReLaunch")) {
                that.getCloseBookshelf();
                wx.setStorageSync("isReLaunch", false)
            }
        }

        that.setData({
            prevPageFlag: 0
        })
    },


    /****
     * 图片异步加载
     */

    loadImages() {
        //同时发起全部图片的加载
        this.data.bookList.forEach(item => {
            this.imgLoader.load(item.imgurl)
        })
    },
    //加载完成后的回调
    imageOnLoad(err, data) {
        const bookList = this.data.bookList.map(item => {
            if (item.imgurl == data.src)
                item.loaded = true
            return item
        })
        this.setData({ bookList })
    },

})